package org.pet.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.pet.entity.Pet;
import org.pet.mapper.PetMapper;
import org.pet.service.PetService;
import org.pet.util.PageBean;
import org.pet.util.Result;
import org.pet.util.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
public class PetServiceImpl implements PetService {

    @Autowired
    private PetMapper petMapper;
    private static final Integer ID = 1;

    @Override
    public Pet getInfoById(Integer id) {
        return petMapper.getInfoById(id);
    }

    @Override
    public Pet getInfoByCategory(String category) {
        return petMapper.getInfoByCategory(category);
    }

    @Override
    public PageBean<Pet> listPage(Integer pageNum, Integer pageSize, String category) {
        //创建PageBean对象
        PageBean<Pet> list = new PageBean<>();
        //开启分页查询 PageHelper , 会自动给查询后面加上limit
        PageHelper.startPage(pageNum,pageSize);
        //获取list
        List<Pet> lists = petMapper.list(category);
        //将返回值转换未page方便获取，返回的分页总数和返回数据列
        Page<Pet> page = (Page<Pet>) lists;

        list.setTotal(page.getTotal());
        list.setItems(page.getResult());
        return list;
    }

    @Override
    @Transactional
    public Result add(Pet pet) {
        return petMapper.insert(pet) == 0 ? Result.error("操作失败") : Result.success();
    }

    @Override
    public Result delete(Integer id) {

        if (check())
            Result.error("无权限");
        return petMapper.delete(id) == 0 ? Result.error("操作失败") : Result.success();
    }

    @Override
    public Result update(Pet pet) {

        if (check())
            Result.error("无权限");
        return petMapper.update(pet) == 0 ? Result.error("操作失败") : Result.success();
    }

//    检测当前用户是否有权限操作宠物
    public boolean check(){
        Map<String,Object> claims = ThreadLocalUtil.get();
        Integer loginId = (Integer) claims.get("id");

        if (!Objects.equals(loginId,ID)){
            return false;
        }
        return true;
    }
}
